import { Store, SessionData } from 'express-session';
import * as Redis from 'ioredis';
import config from '../config';

export class SessionStore extends Store {
  
  private redis: Redis.Redis;

  constructor() {
    super();
    this.redis = new Redis({
      host: config.redis.host,
      port: config.redis.port,
      db: config.redisDb.session,
      password: config.redis.password,
    });
  }

  async get(sid: string, callback: (err: any, session?: SessionData | null) => void) {
    callback(null, JSON.parse(await this.redis.get(sid)))
  }

  async set(sid: string, session: SessionData, callback?: (err?: any) => void) {
    console.log('set');
    
    await this.redis.set(sid, JSON.stringify(session));
    callback();
  }

  async destroy(sid: string, callback?: (err?: any) => void) {
    await this.redis.del(sid);
    callback();
  }

}
